import { _decorator, Component, director, Label, Node, ProgressBar, Scene, SceneAsset } from 'cc';
import { AudioMgr } from './AudioMgr';
const { ccclass, property } = _decorator;

@ccclass('LoadingController')
export class LoadingController extends Component {

    @property(ProgressBar)
    private progressbar: ProgressBar = null;
    @property(Label)
    private progressLable: Label = null;
    @property(Node)
    private gameName: Node = null;

    private welcome = true
    public sceneName = "HomeScene"

    protected onLoad(): void {
        let passedParams = window.globalParam;
        if (passedParams) {
            window.globalParam = null
            this.sceneName = passedParams.sceneName;
            this.welcome = false
        } else {
            this.welcome = true 
        }
    }

    start() {
        this.gameName.active = this.welcome
        setTimeout(() => {
            this.progressLable.string = "Almost done"
            let self = this;

            director.preloadScene(this.sceneName, (completedCount: number, totalCount: number, item: any) => {
                let proInt = (completedCount / totalCount).toFixed(2)
                if (parseFloat(proInt) > this.progressbar.progress) {
                    this.progressbar.progress = parseFloat(proInt)
                    this.progressLable.string = ((parseFloat(proInt) * 100).toFixed(0)) + "%"
                }
            }, (error: null | Error, sceneAsset?: SceneAsset) => {
                if (!error) {
                    console.debug("Scene加载完成")
                    director.loadScene(this.sceneName)
                } else {
                    console.debug("Scene加载失败:" + error.message)
                }
            })
        }, 1000);
        if (this.welcome) {
            AudioMgr.inst.play("musics/worldscenebgm", 1, true)
        }
    }

    update(deltaTime: number) {

    }
}


